const _ = require('lodash');
const fs = require('fs');
const uuidv4 = require('uuid/v4');
const foodItemModel = require('../../app/models/foodItems.json');

module.exports = {
    getFoodItems : getFoodItems,
    getFoodItemByName : getFoodItemByName,
    getFoodItemByProducer: getFoodItemByProducer,
    getFoodItemByNameAndProducer:getFoodItemByNameAndProducer,
    addFoodItem:addFoodItem,
    deleteFoodByItemId:deleteFoodByItemId
}

function getFoodItemByName(name, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(name, item.name)) {
            result = item;
        }
    })
    callback(null, result);
}

function getFoodItems(callback){
    let result = new Array();
    _.forEach(foodItemModel,(item)=>{
        result.push(item);
    })
    callback(null,result);
}

function getFoodItemByProducer(producer, callback) {
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer)) {
            result = item;
        }
    })
    callback(null, result);
}

function getFoodItemByNameAndProducer(name,producer,callback){
    let result = null;
    _.forEach(foodItemModel, (item) => {
        if (_.isEqual(producer, item.producer)&&_.isEqual(name,item.name)) {
            result = item;
        }
    })
    callback(null, result);
}

function addFoodItem(item,callback){
    item.itemId = uuidv4();
    let date = new Date().toLocaleString();
    item.createDatetime = date;
    item.updateDatetime = date;
    foodItemModel.push(item);
    refreshDB(foodItemModel,(error)=>{
        callback(error,item);
    });
    
}

function deleteFoodByItemId(itemId,callback){
    let result = {};
    _.remove(foodItemModel,(item)=>{
        return _.isEqual(itemId,item.itemId);
    });
    refreshDB(foodItemModel,(error)=>{
        callback(error,result);
    });
   
}

function refreshDB(data,callback){
    fs.writeFile('./app/models/foodItems.json',JSON.stringify(data,null,4),(error)=>{
        callback(error);
    });
}